package com.transcargo.request;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.data.Cache;
import com.transcargo.distance.Distance;
import com.transcargo.geo.GeoObjectNotFoundException;
import com.transcargo.rpc.RPCOutput;
import com.transcargo.users.ShortUser;
import com.transcargo.users.User;
import com.transcargo.users.UserNotFoundException;

public class GetDistanceRequest extends Request {
	private String cityFrom = "";
	private String cityTo = "";
	private String fastWay = "";
	private String bigCities = "";
	private String xml = "";
	private static Logger logger = Logger.getLogger(GetDistanceRequest.class);

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
    	cityFrom = request.getParameter("cityFrom");
		if (cityFrom == null) cityFrom = "";
		cityTo = request.getParameter("cityTo");
		if (cityTo == null) cityFrom = "";
		fastWay = request.getParameter("fastWay");
		if (fastWay == null) fastWay = "";
		bigCities = request.getParameter("bigCities");
		if (bigCities == null) bigCities = "";
    }
    private void servletValidateValues() throws ServletValidationException {
    	if (cityFrom.length() == 0) throw new ServletValidationException("Empty cityFrom");
    	if (cityTo.length() == 0) throw new ServletValidationException("Empty cityTo");
    }
    private void servletExecuteRequest() throws ServletRequestException {
    	try {
    		Distance distance = new Distance();
    		distance.CalculateDistance(cityFrom, cityTo, fastWay.equals("on"), bigCities.equals("on"));
    		xml =  RPCOutput.generate(distance);
    	} catch (Exception e) {
    		logger.error("Exception: " + e.getMessage());
    		throw new ServletRequestException();
		}
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();
            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}

